<?php

namespace app\api\controller\bargain;

use app\api\controller\Controller;
use app\api\model\bargain\Active as ActiveModel;
use app\api\model\bargain\Task as TaskModel;
use app\api\model\bargain\Setting as SettingModel;
use app\api\model\Goods as GoodsModelc;
use app\common\library\Lock;
use think\Db;
use app\store\model\Wxapi;
use app\store\model\UploadFile as UploadFileModel;

class Task extends Controller
{
    /**
     * 我的砍价列表
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $model = new TaskModel;
        $myList = $model->getMyList($this->getUser()['user_id']);
        return $this->renderSuccess(compact('myList'));
    }

    /**
     * 创建砍价任务
     * @param $active_id
     * @param $goods_sku_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function partake($active_id, $goods_sku_id)
    {
        // 用户信息
        $user = $this->getUser();

        //判断是否能购买
//        $model = new ActiveModel;
//        $active = $model->getDetail($active_id);
//        $checkUserBuy_err = $this->checkUserBuy($active['goods_id'],1,1);
//        if($checkUserBuy_err){
//            return $this->renderError($checkUserBuy_err);
//        }

        if ($user['is_black'] == 2) {
            return $this->renderError('账号存在异常,不能发起砍价');
        }

        // 创建砍价任务
        $model = new TaskModel;
        if (!$model->partake($user['user_id'], $active_id, $goods_sku_id)) {
            return $this->renderError($model->getError() ?: '砍价任务创建失败');
        }
        return $this->renderSuccess([
            'task_id' => $model['task_id']
        ]);
    }

    /**
     * 获取砍价任务详情
     * @param $task_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($task_id)
    {
        $model = new TaskModel;
        $detail = $model->getTaskDetail($task_id, $this->getUser(false));
        if ($detail === false) {
            return $this->renderError($model->getError());
        }
        // 砍价规则
        $setting = SettingModel::getBasic();
        // 获取自定义广告
        // $ads = (new UploadFileModel)->getList(10006, '', 0);
        $ads = db('ads')->where('type',1)->select();
        // 当前登录的用户
        // $user = $this->getUser();
        
        return $this->renderSuccess(array_merge($detail, ['setting' => $setting,'ads'=>$ads]));
    }

    /**
     * 帮砍一刀
     * @param $task_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function help_cut($task_id)
    {
        // 加阻塞锁, 防止并发
        Lock::lockUp("bargain_help_cut_{$task_id}");
        // 砍价任务详情
        $model = TaskModel::detail($task_id);
        // 砍一刀的金额
        $cut_money = $model->getCutMoney();
        // 帮砍一刀事件
        $status = $model->helpCut($this->getUser());
        // 解除并发锁
        Lock::unLock("bargain_help_cut_{$task_id}");
        if ($status == true) {
            return $this->renderSuccess(compact('cut_money'), '砍价成功');
        }
        return $this->renderError($model->getError() ?: '砍价失败');
    }

    /**
     * @param $goods_id
     * @param $goods_num
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * 判断用户能否购买
     */
    private function checkUserBuy($goods_id,$goods_num,$type){
        // 用户信息
        $user = $this->getUser();
        /*判断此用户能否购买start*/
        $goods = GoodsModelc::detail($goods_id);
        if($goods['buy_number'] > 0){
            //当前商品如果有限购数量
            $order_goods_num = Db::table('yoshop_order_goods')
                ->join('order','order.order_id = yoshop_order_goods.order_id')
                ->where('order.pay_status','=',20)
                ->where('yoshop_order_goods.user_id','=',$user['user_id'])
                ->where('order.order_source','=',10)
                ->where('yoshop_order_goods.goods_id','=',$goods_id)
                ->sum('total_num');
            if(($goods_num + $order_goods_num) > $goods['buy_number']){
                if($type == 2){
                    return '很抱歉，商品['.$goods['goods_name'].']限购'.$goods['buy_number'].'次，您已超限';
                }else{
                    return '本商品限购'.$goods['buy_number'].'次，您已超限';
                }
            }
        }
        $buy_grade = $goods['buy_grade'] ? json_decode($goods['buy_grade']) : '';
        //限制会员等级
        if(is_array($buy_grade)){
            if(isset($buy_grade[0])){
                if(intval($buy_grade[0])){
                    //限制会员等级
                    if(!in_array($user['grade_id'],$buy_grade)){
                        $user_grade_data = Db::table('yoshop_user_grade')->where('grade_id','in',$buy_grade)->order('weight asc')->find();
                        return '您不是'.$user_grade_data['name'].'，无法下单，请开通再来！';
                    }
                }
            }
        }
        /*判断此用户能否购买end*/

        //限制新用户购买
        if($goods['buy_limit_new'] == 2){
            if(Db::table('yoshop_order')->where('pay_status','=',20)
                ->where('user_id','=',$user['user_id'])
                ->where('order_source','=',10)->find()){
                $order_success_num = Db::table('yoshop_order')
                    ->where('pay_status','=',20)
                    ->where('user_id','=',$user['user_id'])
                    ->where('order_source','=',10)
                    ->count();
            }else{
                $order_success_num = 0;
            }
            $order_success_num = $order_success_num ? $order_success_num : 0;
            if($order_success_num > 1){
                return '该商品仅限新用户购买！';
            }
        }

        //用户被拉黑，不能支付
        if($user['is_black'] == 2){
            return '涉嫌违规操作，无法继续操作！';
        }

    }

    /**
     * 检测用户等级
     */
    public function checkgrade(){
        $goods_id = $this->request->param('goods_id');
        if($goods_id){
            $goods = GoodsModelc::detail($goods_id);
            $buy_grade = $goods['buy_grade'] ? json_decode($goods['buy_grade']) : array();
            $buy_grade = array_filter($buy_grade);
            if(is_array($buy_grade)){
                if(isset($buy_grade[0])){
                    if(intval($buy_grade[0])){
                        //限制会员等级
                        if(!in_array($this->user['grade_id'],$buy_grade)){
                            $user_grade_data = Db::table('yoshop_user_grade')->where('grade_id','in',$buy_grade)->order('weight asc')->find();
                            return $this->renderError('您不是'.$user_grade_data['name'].'，无法下单，请开通再来！');
                        }
                    }
                }
            }
            return $this->renderSuccess('无限制');
        }
    }
    


}